package cn.da.shuai.cool.system.model.validator;


import cn.da.shuai.cool.system.model.annotation.PasswordValidation;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.passay.*;

public class PasswordValidator implements ConstraintValidator<PasswordValidation, String> {

    @Override
    public void initialize(PasswordValidation constraintAnnotation) {
        // 可以在这里初始化一些参数，如果有的话
    }
 
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return false;
        }

        PasswordData passwordData = new PasswordData(value);
        RuleResult result = PasswordValidatorHolder.passwordValidator.validate(passwordData);
//        System.out.println(PasswordValidatorHolder.passwordValidator.getMessages(result));
        return result.isValid();
    }

    private static class PasswordValidatorHolder {

        public static final org.passay.PasswordValidator passwordValidator = new org.passay.PasswordValidator(
                new LengthRule(6, 20), // 长度在6-20之间
                new CharacterCharacteristicsRule(
                        3,
                        new CharacterRule(EnglishCharacterData.UpperCase, 1), // 包含大写字母
                        new CharacterRule(EnglishCharacterData.LowerCase, 1), // 包含小写字母
                        new CharacterRule(EnglishCharacterData.Digit, 1), // 包含数字
                        new CharacterRule(EnglishCharacterData.Special, 1) // 包含特殊字符
                ),
                new WhitespaceRule(new char[]{0x20})
        );
    }
}
